package config

import (
	"fmt"
	"log"
	"path"
	"runtime"

	"github.com/sirupsen/logrus"
	"github.com/spf13/viper"
)

const (
	TimeFormat = "2006-01-02 15:04:05"
)

var (
	Port       string // 服务端口
	JwtKey     string // jwt加密secret
	JwtExpTime int64  // token过期时间
	Username   string // 用户名
	Password   string //密码
)

type RespData struct {
	Status  int                    `json:"status"`
	Message string                 `json:"message"`
	Data    map[string]interface{} `json:"data"`
}

// 定义构造函数，初始化响应数据
func NewRespData() RespData {
	respData := RespData{}
	respData.Status = 200
	data := make(map[string]interface{})
	respData.Data = data
	return respData
}

// 定义日志级别
func initLogConfig(loglevel string) {
	switch {
	case loglevel == "debug":
		logrus.SetLevel(logrus.DebugLevel)
	case loglevel == "error":
		logrus.SetLevel(logrus.ErrorLevel)
	case loglevel == "warning":
		logrus.SetLevel(logrus.WarnLevel)
	case loglevel == "info":
		logrus.SetLevel(logrus.InfoLevel)
	default:
		logrus.SetLevel(logrus.InfoLevel)
	}
}

func init() {
	logrus.SetFormatter(&logrus.JSONFormatter{
		TimestampFormat: TimeFormat,
		CallerPrettyfier: func(f *runtime.Frame) (function string, file string) {
			fileName := path.Base(f.File)
			return f.Function, fileName
		},
	})
	// 打印日志时提添加文件和行号
	logrus.SetReportCaller(true)
	viper.SetDefault("PORT", "8088")
	viper.SetDefault("JWT_KEY", "gindemo")
	viper.SetDefault("JWT_EXP_TIME", 120)
	viper.SetDefault("LOG_LEVEL", "debug")
	viper.SetDefault("USERNAME", "admin")
	viper.SetDefault("PASSWORD", "123456")
	//会获取设置的默认配置
	// viper.AutomaticEnv()
	fmt.Println("开始加载配置程序")
	loglevel := viper.GetString("LOG_LEVEL")
	initLogConfig(loglevel)
	Port = viper.GetString("PORT")
	JwtKey = viper.GetString("JWT_KEY")
	JwtExpTime = viper.GetInt64("JWT_EXP_TIME")
	Username = viper.GetString("USERNAME")
	Password = viper.GetString("PASSWORD")
	log.Printf("Username: %s,Password: %s", Username, Password)
}
